1029C - Maximal Intersection - CodeForces Solution


greedy math sortings *1600

Please click on ads to support us..

Python Code:


n=int(input())
l=[]
for i in range(n):
    l.append(list(map(int, input().split())))

ll=[[0,0] for _ in range(n)]
rr=[[0,0] for _ in range(n)]
ll[0]=l[0]
for i in range(1,n):
    ll[i][0]=max(ll[i-1][0],l[i][0])
    ll[i][1]=min(ll[i-1][1],l[i][1])
    
rr[-1]=l[-1]
for i in range(n-2,-1,-1):
    rr[i][0]=max(rr[i+1][0],l[i][0])
    rr[i][1]=min(rr[i+1][1],l[i][1])

ans=0
if n>1:
    ans=max(ans,rr[1][1]-rr[1][0])
    ans=max(ans,ll[n-2][1]-ll[n-2][0])
for i in range(1,n-1):
            ans=max(ans, min(ll[i-1][1],rr[i+1][1])-max(ll[i-1][0], rr[i+1][0]))
print(ans)

    

C++ Code:

// بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ
// Written by Ilia Rahbar

// #pragma GCC optimize ("O3,no-stack-protector,unroll-loops,fast-math")
// #pragma GCC target ("abm,bmi,bmi2,tbm,avx2")

#include <bits/stdc++.h>
using namespace std;

#define int int64_t
#define sz(x) int(x.size())
#define ai(x) array <int, x>
#define be(x) x.begin(), x.end()
#define pb push_back
#define el '\n'
#define sp ' '
#define fi first 
#define se second

const int M = 1e9 + 7, N = 1e6 + 100;

int n, ans = 0, x, y;

ai(2) a[N], l[N], r[N];

int32_t main()
{
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    
    cin >> n;

    for (int i = 0; i < n; i++)
        cin >> a[i][0] >> a[i][1];

    l[0] = a[0];

    for (int i = 1; i < n; i++)
        l[i][0] = max(l[i-1][0], a[i][0]), l[i][1] = min(l[i-1][1], a[i][1]);

    r[n-1] = a[n-1];

    for (int i = n-2; i >= 0; i--)
        r[i][0] = max(r[i+1][0], a[i][0]), r[i][1] = min(r[i+1][1], a[i][1]);

    for (int i = 1; i < n-1; i++)
    {
        x = max(r[i+1][0], l[i-1][0]);
        y = min(r[i+1][1], l[i-1][1]);

        ans = max(ans, y - x);
    }

    cout << max(ans, max(r[1][1] - r[1][0], l[n-2][1] - l[n-2][0]));
}


Comments

Submit
0 Comments
More Questions

2B - The least round way
1324A - Yet Another Tetris Problem
246B - Increase and Decrease
22E - Scheme
1566A - Median Maximization
1278A - Shuffle Hashing
1666F - Fancy Stack
1354A - Alarm Clock
1543B - Customising the Track
1337A - Ichihime and Triangle
1366A - Shovels and Swords
919A - Supermarket
630C - Lucky Numbers
1208B - Uniqueness
1384A - Common Prefixes
371A - K-Periodic Array
1542A - Odd Set
1567B - MEXor Mixup
669A - Little Artem and Presents
691B - s-palindrome
851A - Arpa and a research in Mexican wave
811A - Vladik and Courtesy
1006B - Polycarp's Practice
1422A - Fence
21D - Traveling Graph
1559B - Mocha and Red and Blue
1579C - Ticks
268B - Buttons
898A - Rounding
1372B - Omkar and Last Class of Math